{ "cells": [ { "cell_type": "markdown", "id": "d240914c", "metadata": {}, "source": [ "## Dictionary Comprehension - Filtering" ] }, { "cell_type": "code", "execution_count": 1, "id": "4fd8fcaa", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5}" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dict1={\n", " 'A':1,\n", " 'B':2,\n", " 'C':3,\n", " 'D':4,\n", " 'E':5\n", "}\n", "dict1" ] }, { "cell_type": "markdown", "id": "a6a76727", "metadata": {}, "source": [ "### Filter based on Values" ] }, { "cell_type": "code", "execution_count": 5, "id": "3c37ebec", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'D': 4, 'E': 5}" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "{x:y for x,y in dict1.items() if y>3} # Note: here x:y is returned instead of x,y because of format of dict we need" ] }, { "cell_type": "markdown", "id": "39c711f6", "metadata": {}, "source": [ "### If else Conditions:" ] }, { "cell_type": "markdown", "id": "bef49a4a", "metadata": {}, "source": [ "- Syntax:{ (x if else):(y if else) for x,y in dict1.items()}" ] }, { "cell_type": "markdown", "id": "ea41ca44", "metadata": {}, "source": [ "#### on Keys" ] }, { "cell_type": "code", "execution_count": 9, "id": "16979a05", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'A': 1, 'B': 2, 'c': 3, 'D': 4, 'E': 5}" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Start by writting normal condition { x:y for x,y in dict1.items()}\n", "{ (x.lower() if x=='C' else x) :y for x,y in dict1.items()}" ] }, { "cell_type": "markdown", "id": "9b86a5f8", "metadata": {}, "source": [ "#### on Values" ] }, { "cell_type": "code", "execution_count": 10, "id": "3cecd8bd", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'A': 1, 'B': 2, 'C': 3, 'D': 160, 'E': 5}" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Start by writting normal condition { x:y for x,y in dict1.items()}\n", "{ x: (y*40 if y==4 else y) for x,y in dict1.items()}" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.8" } }, "nbformat": 4, "nbformat_minor": 5 }